package com.fingard.dsp.bank.directbank.bochk01;

import java.util.ArrayList;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextWriter;

public class BOCHK01Base extends DirectBase {

    private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime14Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    private static TransIDHelper idHelper2 = new TransIDHelper(1, 99);

    protected String getQryTransID2() {
        Date tmpDateNow = new Date();
        return Format.DateTime14Format.format(tmpDateNow) + idHelper2.getNextIDStr();
    }

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    protected String[] sendToBank(String p_reqStr) throws Exception {
        String[] retStr = new String[]{"", ""};

        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverURL);
        WriteBankLogStep2(p_reqStr);
        //设置https协议
        System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
        WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/xml;charset="+getCharset());
        tmpWebRequest.setRequestProperty("connection", "Close");
        String charsetName = getCharset();
        byte[] tmpToWriteBytes = p_reqStr.getBytes(charsetName);
        retStr = tmpWebRequest.upload(tmpToWriteBytes, charsetName);
        WriteBankLogStep3(retStr[1]);

        return retStr;
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, BOCHK01Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.packageId)) {
            throw new Exception("未赋值packageId");
        }
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("BOCHKE2B");
        xmlWriter.writeStartElement("Head");
        xmlWriter.writeElementString("PackageId", p_bankHeader.packageId);//包序列 ID
        xmlWriter.writeElementString("CBSAcctNo", bankFront.org);//客�糁秀y企�I�W上�y行�~�籼��a
        xmlWriter.writeElementString("UserId", bankFront.operator);//客�舻侨胫秀y企�I�W上�y行用�裘��Q
        xmlWriter.writeElementString("Password", bankFront.loginPasswd);//私人密�a
        xmlWriter.writeElementString("NewPwd", "");//新密�a
        xmlWriter.writeElementString("ConfirmNewPwd", "");//�_�J新密�a
        xmlWriter.writeElementString("ECertName", bankFront.ownKeyStorePath);//�子�C��CN值
        xmlWriter.writeElementString("ECertPwd", bankFront.ownKeyPassword);//�子�C��密�a
        xmlWriter.writeEndElement();
        xmlWriter.writeStartElement("Tx");
    }

    protected ArrayList<String> cutAddrString(String p_str, int p_maxLine) throws Exception {
        ArrayList listLine = new ArrayList();
        String tmpStr = p_str.trim();
        if (tmpStr != null && tmpStr.length() > 0) {
            int lastIdx = 0;
            int lastCount = 0;
            int maxLen = 35;
            int loopi = 0;
            int lastChsIdx = -1;//上一个中文字所在位置
            int numSeriesCount = 0;//连续
            while (loopi < tmpStr.length()) {
                int i = loopi;
                byte[] charBytes = (tmpStr.charAt(i) + "").getBytes(getCharset());
                int countB = charBytes.length;
                if (countB > 1) {
                    countB = 5;//一个汉字算5
                    lastChsIdx = i;
                    numSeriesCount = 0;
                } else if (charBytes[0] >= 48 && charBytes[0] <= 57) {
                    //是数字，ASCII码为48到57
                    numSeriesCount++;
                    if (numSeriesCount == 4)//连续4个数字，判断前后是否为中文
                    {
                        if (lastChsIdx == i - 4)//前面是中文
                        {
                            if (tmpStr.length() - 1 > i) {
                                int nextBCount = (tmpStr.charAt(i + 1) + "").getBytes(getCharset()).length;
                                if (nextBCount > 1) {
                                    //后面也是中文
                                    countB = 2;//计数加1
                                }
                            }
                        }
                    }
                } else {
                    numSeriesCount = 0;
                }
                if (lastCount + countB >= maxLen || i == tmpStr.length() - 1)//需换行
                {
                    int endIdx = 0;
                    if (lastCount + countB > maxLen) {
                        endIdx = i - 1;
                        loopi = i - 1;//个数超了，当前字符不计入本行，下次循环从当前开始，这里需减一
                    } else {
                        endIdx = i;
                    }
                    //判断下一行开头不能以空格和/打头
                    int cutIdx = endIdx;
                    while (cutIdx < tmpStr.length() - 1 && cutIdx >= lastIdx && (tmpStr.charAt(cutIdx + 1) == ' ' || tmpStr.charAt(cutIdx + 1) == '/')) {
                        cutIdx--;
                    }
                    if (cutIdx >= lastIdx) {
                        endIdx = cutIdx;
                        loopi = endIdx;
                    }
                    listLine.add(tmpStr.substring(lastIdx));
                    if (listLine.size() >= p_maxLine) {
                        return listLine;
                    }
                    lastIdx = endIdx + 1;
                    lastCount = 0;
                } else {
                    lastCount += countB;
                }
                loopi++;
            }
        }
        if (listLine.size() == 0) {
            listLine.add("");
        }
        return listLine;
    }

    protected void spiltToLine(XElement p_XElement, String pStrValue, int pMaxLine) throws Exception {
        ArrayList listLine = cutAddrString(StringHelper.trimStart(StringHelper.trimStart(pStrValue, " "), "/"), pMaxLine);
        for (Object eachLine : listLine) {
            String tmpEachLine = eachLine.toString();
            if (tmpEachLine.length() > 0) {
                p_XElement.addChild(new XElement("Line", tmpEachLine));
            } else if (listLine.size() == 1) {
                p_XElement.addChild(new XElement("Line", tmpEachLine));
            }
        }
    }

    protected void spiltToLine(XElement p_XElement, ArrayList<String> pStrValue) throws Exception {
        for (String tmpEachLine : pStrValue) {
            if (tmpEachLine.length() > 0) {
                p_XElement.addChild(new XElement("Line", tmpEachLine));
            }
        }
    }

}
